import luckysheetformula from '../global/formula'
import { getDictData } from '../global/dictRenderData'

//Protect sheet initial
window.initCellDict = function(position, type, cellOp) {
  let activeData = getDictData(cellOp.value1, cellOp.value2)
  if (activeData) {
    let left
    let top
    let height
    let width
    if (type == 1) {
      left = position.left
      top = position.top
      width = position.width
      height = position.height
    } else {
      let obj = document
        .getElementById('luckysheet-cell-selected')
        .getBoundingClientRect()
      left = obj.left
      top = obj.top - 4
      height = obj.height
      width = obj.width -8
    }
    if (!document.getElementById('luckysheet-modal-dialog-slider-cellDict')) {
      const protectionModalHtml = `
        <div id="luckysheet-modal-dialog-slider-cellDict" style="max-height:500px;min-width: 200px;background: #fff;overflow: auto">  
          <!-- <div id="luckysheet-dataVerification-dropdown-btn"></div> -->
          <div id="dataconfigmouseDict" style="margin-top: 10px;"></div>
        </div>`
      $('body')
        .first()
        .append(protectionModalHtml)
    }
    $('#luckysheet-modal-dialog-slider-cellDict').show()
    $('#dataconfigmouseDict').empty()
    let p = $('#luckysheet-modal-dialog-slider-cellDict')
    top = top == '-10000' ? 0 : top
    p.css({
      top: top + height + 4 + 'px',
      left: left + 'px',
      width: width + 8 + 'px',
    })
    let ChildList = ''
    const l = activeData.length
    for (let i = 0; i < l; i++) {
      ChildList += `<div class="dropdown-List-item" id="${activeData[i].itemCode}">${activeData[i].itemName}</div>`
    }
    $('#dataconfigmouseDict').append(ChildList)
    addFunc(position.r, position.c)
  }
}
function addFunc(r, c) {
  $('#dataconfigmouseDict .dropdown-List-item').on('click', function(e) {
    window.luckysheet.exitEditMode()
    event.stopPropagation()
    setTimeout(() => {
      const MD = e.target.innerText
      luckysheetformula.updatecell(r, c, { m: MD, v: MD })
      closeProtectionModal()
    }, 50)
  })
  $('#dataconfigmouseDict').on('click', function() {
    event.stopPropagation()
  })
  $('#luckysheet-modal-dialog-protection-close').on('click', function() {
    closeProtectionModal()
  })
  $('body').on('click', function() {
    closeProtectionModal()
  })
}

function closeProtectionModal() {
  $('#luckysheet-modal-dialog-slider-cellDict').hide()
}
